package gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import util.Search;

public class SearchGUI {
	public static String getMeal(final String dict[], Component parent) {
		final JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		final JList meals = new JList(dict);
		final JTextField search = new JTextField();
		search.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void changedUpdate(DocumentEvent de) {
				meals.setListData(Search.search(search.getText(), dict));
			}

			@Override
			public void insertUpdate(DocumentEvent de) {
				meals.setListData(Search.search(search.getText(), dict));
			}

			@Override
			public void removeUpdate(DocumentEvent de) {
				meals.setListData(Search.search(search.getText(), dict));
			}
		});

		panel.add(search,BorderLayout.NORTH);
		panel.add(new JScrollPane(meals),BorderLayout.CENTER);
		search.requestFocusInWindow();
		int result=JOptionPane.showOptionDialog(parent,panel, "Pick Meal",
				JOptionPane.PLAIN_MESSAGE,JOptionPane.PLAIN_MESSAGE,null,
				new String[] {"Cancel","Select"},"Select");
		Object ret = null;
		if(result==1) {
			ret = meals.getSelectedValue();
			if(ret==null) ret=meals.getModel().getElementAt(0);
		}
		return (String)ret;
	}
}
